package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.to.KilledInfo;
import com.alibaba.fastjson.JSON;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@RocketMQMessageListener(consumerGroup = "kill-service-consumer",
        topic = BaseConstants.Kill.TOPIC_KILL_PAY_OUT_TIME,
        selectorExpression = BaseConstants.Kill.TAG_KILL_PAY_OUT_TIME)
@Component
@Slf4j
public class KillOutTimeConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate ;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void onMessage(MessageExt message) {
        log.info("尝试检查秒杀下单超时...");
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        KilledInfo killedInfo = JSON.parseObject(msg,KilledInfo.class);
        String orderNo = killedInfo.getOrderNo();

        KilledInfo killedInfoFromRedis = (KilledInfo) redisTemplate.opsForValue().get(BaseConstants.Kill.KEY_KILLED_INFO + orderNo+":"+killedInfo.getUserId());
        log.info("拿到Redis中的秒杀信息 {}",killedInfoFromRedis);
        if(killedInfoFromRedis != null){
            //超时了，Redis中还存在秒杀信息，说明还没去下单，退库存处理
            RSemaphore semaphore = redissonClient.getSemaphore(BaseConstants.Kill.KEY_KILL_STORE + killedInfoFromRedis.getKillCourseId().toString());
            semaphore.addPermits(killedInfoFromRedis.getKillCount());
            //删除秒杀资格
            redisTemplate.delete(BaseConstants.Kill.KEY_KILLED_INFO + orderNo+":"+killedInfo.getUserId());
            log.info("秒杀超时，删除秒杀资格 {}",killedInfoFromRedis);

            //删除秒杀记录，用户可以进行二次秒杀
            redisTemplate.delete(BaseConstants.Kill.KEY_KILLLOG+killedInfoFromRedis.getUserId()+":"+killedInfoFromRedis.getKillCourseId());
            log.info("秒杀超时，退回库存数 {} ,删除用户　{} 的秒杀记录 ",killedInfoFromRedis.getKillCount() ,killedInfoFromRedis.getUserId() );
        }

    }
}
